package edu.csu.smartpark.shiro;

import edu.csu.smartpark.util.JwtUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/*
* @Description: 负责校验jwt token的realm
* @Author: LZY
* @Date: 2021/4/19 22:05
*/
public class JwtRealm extends AuthorizingRealm {

    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public boolean supports(AuthenticationToken token) {
        //这个token就是从过滤器中传入的jwtToken
        return token instanceof JwtToken;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //认证
        //这个token就是从过滤器中传入的jwtToken
        String jwt = (String) token.getPrincipal();
        if (jwt != null && !jwtUtil.isVerify(jwt)) {
            throw new IncorrectCredentialsException("Authorization token is invalid");
        }
        return new SimpleAuthenticationInfo(jwt, jwt, "JwtRealm");
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        principals.getPrimaryPrincipal();
        String jwt = (String) principals.getPrimaryPrincipal();

        String role = (String) jwtUtil.decode(jwt).get("role");

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addRole(role);
        return authorizationInfo;
    }
}

